﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.IO;
using System.ComponentModel;
using System.Threading;

namespace System.Windows.Media.DirectShow.Filters
{
    public class MediaSourceAsync : BaseFilter, IUriSourceFilter, IStreamSourceFilter
    {
        private Uri _currentUri;
        private WebRequest request;
        private Stream _stream;
        private AsyncOperation loadOperation;

        public MediaSourceAsync()
        {

        }

        public override string Name
        {
            get { return "Media Source Async"; }
        }

        public event AsyncCompletedEventHandler LoadCompleted;

        public Uri CurrentUri
        {
            get
            {
                return _currentUri;
            }
            private set
            {
                _currentUri = value;
            }
        }


        #region IStreamSourceFilter Members

        public Stream CurrentStream
        {
            get { return _stream; }
        }

        public void LoadAsync(Stream stream)
        {
            if (stream == null)
                throw new ArgumentNullException("stream");
            if (this.State != FilterState.Stopped)
                throw new InvalidOperationException("Filter is currently running");

            _currentUri = null;
            _stream = stream;

            loadOperation = AsyncOperationManager.CreateOperation(null);

            ThreadPool.QueueUserWorkItem(s =>
            {
                try
                {
                    OnStreamAvailable(_stream);

                    OnLoadCompleted(new AsyncCompletedEventArgs(null, false, null));
                }
                catch (Exception e)
                {
                    OnLoadCompleted(new AsyncCompletedEventArgs(e, false, null));
                }
            });
        }

        #endregion

        public void LoadAsync(Uri uri)
        {
            if (this.State != FilterState.Stopped)
                throw new InvalidOperationException("Filter is currently running");

            this.CurrentUri = EnsureAbsolute(uri);

            loadOperation = AsyncOperationManager.CreateOperation(null);
            ThreadPool.QueueUserWorkItem(s => Load());
        }

        protected virtual void OnLoadCompleted(AsyncCompletedEventArgs e)
        {
            if (LoadCompleted != null)
                loadOperation.PostOperationCompleted(s => LoadCompleted(this, e), null);
        }

        private void Load()
        {
            if (_stream != null)
                _stream.Dispose();

            request = WebRequest.Create(this.CurrentUri);
            request.BeginGetResponse(OnGetResponse, null);
        }

        private void OnGetResponse(IAsyncResult ar)
        {
            try
            {
                WebResponse response = request.EndGetResponse(ar);
                _stream = response.GetResponseStream();

                OnStreamAvailable(_stream);

                OnLoadCompleted(new AsyncCompletedEventArgs(null, false, null));
            }
            catch (Exception e)
            {
                HandleException(e);

                OnLoadCompleted(new AsyncCompletedEventArgs(e, false, null));
            }
        }

        /// <summary>
        /// Get the internal stream used to read data
        /// </summary>
        public Stream BaseStream
        {
            get { return _stream; }
        }

        protected virtual void OnStreamAvailable(Stream stream)
        {

        }

        private void HandleException(Exception e)
        {
            var d = new DirectShowFilterException("Error reading stream", this, e);
            if (this.Graph is IMediaEvent)
                ((IMediaEvent)this.Graph).NotifyEvent(new ErrorEventArgs(this, e));
            else
                throw d;
        }

        private static Uri EnsureAbsolute(Uri uri)
        {
            if (!uri.IsAbsoluteUri)
                return new Uri(new System.Windows.Interop.SilverlightHost().Source, uri);
            else
                return uri;
        }

        protected override void RunInternal(TimeSpan start)
        {
            if (this.CurrentStream == null)
                throw new InvalidOperationException("No uri or stream loaded for this filter");

            base.RunInternal(start);
        }


    }
}
